package com.fch.sdlibrary.security;

import com.fch.sdlibrary.api.BaseResponse;
import com.fch.sdlibrary.entity.User;
import com.fch.sdlibrary.mapper.UserMapper;
import com.google.gson.Gson;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.stream.Collectors;

/**
 * @program: sdlibrarySpring
 * @description: 自定义登录成功
 * @CreatedBy: fch
 * @create: 2022-05-09 10:21
 **/
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    UserMapper userMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        User user = (User) userMapper.findOneByUserName(request.getParameter("username"));
        //获取用户名
        String userName = user.getUsername();
        //获取user中角色
        String role = user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(","));
        //生成token
        String token = JwtUtils.generatorToken(userName, role);
        response.addHeader("token", token);


        //返回登陆成功信息
        response.setContentType("application/json;charset=utf-8");
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setCode(0);
        baseResponse.setMsg("成功");
        user.setUserPasw("");
        baseResponse.setData(user);
        Gson gson = new Gson();
        try (PrintWriter out = response.getWriter()) {
            out.write(gson.toJson(baseResponse));
            out.close();
            out.flush();
        }
    }
}
